07. Adding markers on long click

L4 A06 Adding Markers On Long Click

Reference Documentation

Add markers on long click

In this step, you add a marker when the user touches and holds a location on the map. You will then add an InfoWindow that displays the coordinates of the marker when the marker is tapped.

  1. Create a method stub in MapsActivity called setMapLongClick() that takes a GoogleMap as an argument. Attach a long click listener to the map object.
private fun setMapLongClick(map:GoogleMap) {
   map.setOnMapLongClickListener { }
}
  1. Inside onMapLongClick(), call the addMarker() method. Pass in a new MarkerOptions object with the position set to the passed-in LatLng:
private fun setMapLongClick(map: GoogleMap) {
   map.setOnMapLongClickListener { latLng ->
       map.addMarker(
           MarkerOptions()
               .position(latLng)
       )
   }
}
  1. At the end of the onMapReady() method, call etMapLongClick(). Pass in map.
override fun onMapReady(googleMap: GoogleMap) {
   …

   setMapLongClick(map)
}
  1. Run the app. Touch and hold on the map to place a marker at a location. Tap the marker, which centers it on the screen.
    When a marker is tapped, navigation buttons appear at the bottom-left side of the screen, allowing the user to use the Google Maps app to navigate to the marked position.

Add an info window for the marker:

  1. In setMapLongClick()’s setOnMapLongClickListener() lambda, create a snippet. A snippet is additional text that is displayed below the title. In your case the snippet displays the latitude and longitude of a marker.
private fun setMapLongClick(map: GoogleMap) {
   map.setOnMapLongClickListener { latLng ->
       // A Snippet is Additional text that's displayed below the title.
       val snippet = String.format(
           Locale.getDefault(),
           "Lat: %1$.5f, Long: %2$.5f",
           latLng.latitude,
           latLng.longitude
       )
       map.addMarker(
           MarkerOptions()
               .position(latLng)
       )
   }
}
  1. Set the title of the marker to “Dropped Pin” and set the marker’s snippet to the snippet you just created.
private fun setMapLongClick(map: GoogleMap) {
   map.setOnMapLongClickListener { latLng ->
       // A Snippet is Additional text that's displayed below the title.
       val snippet = String.format(
           Locale.getDefault(),
           "Lat: %1$.5f, Long: %2$.5f",
           latLng.latitude,
           latLng.longitude
       )
       map.addMarker(
           MarkerOptions()
               .position(latLng)
               .title(getString(R.string.dropped_pin))
               .snippet(snippet)

       )
   }
}
  1. Run the app. Touch and hold on the map to drop a location marker. Tap the marker to show the info window.